package com.sunny.shop.core;

import com.sunny.shop.core.configuration.ExceptionCodeConfiguration;
import com.sunny.shop.exception.httpe.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.List;

@ControllerAdvice // 标明这是一个全局异常处理类，加入到容器中,基类exception
public class GlobalException {
    private ExceptionCodeConfiguration codeConfiguration;

    @Autowired // 通过这个注解将配置类读取出来
    public void setCodeConfiguration(ExceptionCodeConfiguration codeConfiguration) {
        this.codeConfiguration = codeConfiguration;
    }

    @ResponseBody
    @ResponseStatus(code= HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = Exception.class) // 异常的处理方法,在外面抛出异常的时候sp会调用此方法
    public UnifyRespones handleException(HttpServletRequest req, Exception e){
        System.out.println(e);
        String requestURI = req.getRequestURI();
        String method = req.getMethod();
        UnifyRespones unifyRespones = new UnifyRespones(99999, "服务器内部错误", method + " " + requestURI);
        return unifyRespones;
    }

    @ExceptionHandler(value = HttpException.class)
    public ResponseEntity<UnifyRespones> handleHttpException(HttpServletRequest req, HttpException e){
        System.out.println(e.getCode());
        String requestURI = req.getRequestURI(); // 获取请求uri
        String method = req.getMethod(); // 请求类型

        UnifyRespones message = new UnifyRespones(e.getCode(), codeConfiguration.getMessage(e.getCode()), method+" "+ requestURI);
        HttpHeaders httpHeaders = new HttpHeaders(); // 使用sp内部提供的httpHeaders设置http响应体
        httpHeaders.setContentType(MediaType.APPLICATION_JSON); // 设置返回类型
        HttpStatus httpStatus = HttpStatus.resolve(e.getHttpStatusCode());// 设置http状态码
        // 通过泛型返回
        ResponseEntity<UnifyRespones> unifyResponesResponseEntity = new ResponseEntity<>(message, httpHeaders, httpStatus);
        return unifyResponesResponseEntity;
    }

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public UnifyRespones handleBeanValidation(HttpServletRequest req, MethodArgumentNotValidException e){
        String requestURI = req.getRequestURI(); // 获取请求uri
        String method = req.getMethod(); // 请求类型
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        String message = this.formatAllErrorMessage(errors);
        UnifyRespones unifyRespones = new UnifyRespones(10001, message, method + " " + requestURI);
        return unifyRespones;
    }

    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public UnifyRespones handleConstraintException(HttpServletRequest req, ConstraintViolationException e){
        String requestURI = req.getRequestURI();
        String method = req.getMethod();
        String message = e.getMessage();
        UnifyRespones unifyRespones = new UnifyRespones(10001, message, method + " " + requestURI);
        return unifyRespones;
    }

    private String formatAllErrorMessage(List<ObjectError> errors){
        StringBuffer errorMessage = new StringBuffer();
        errors.forEach(error->errorMessage.append(error.getDefaultMessage()).append(";"));
        return errorMessage.toString();
    }
}
